package com.task.service.impl;

import com.task.common.exception.UserException;
import com.task.common.util.constant.Constants;
import com.task.common.entity.sys.SysUser;
import com.task.common.exception.user.CaptchaException;
import com.task.common.exception.user.CaptchaExpireException;
import com.task.common.util.redis.RedisCache;
import com.task.common.entity.sys.model.RegisterBody;
import com.task.common.util.body.CommonModel;
import com.task.common.util.body.ModelTool;
import com.task.common.util.string.StringUtils;
import com.task.service.IUserService;
import com.task.service.RegisterService;
import com.task.common.util.security.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author Huzz
 * @created 2021-11-30 18:26
 */
@Slf4j
@Service
public class RegisterServiceImpl implements RegisterService {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IUserService userService;

    @Override
    public CommonModel register(RegisterBody user) {
        CommonModel result = ModelTool.createModel();
        String username = user.getUsername();
        String password = user.getPassword();

        /** 校验验证码 */
        try {
            validateCaptcha(username, user.getCode(), user.getUuid());
        } catch (UserException e){
            return result.fail(e.getMessage());
        }

        /** 校验是否合法 */
        if (StringUtils.isEmpty(username)) {
            result.fail("用户名不能为空");
        } else if (StringUtils.isEmpty(password)) {
            result.fail("用户密码不能为空");
        } else if (StringUtils.isNull(userService.findUserByUsername(username))) {
            /** 创建用户对象 */
            SysUser sysUser = new SysUser();
            sysUser.setUsername(username);
            sysUser.setNickname(username);
            sysUser.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
            boolean regFlag = userService.register(sysUser);
            if (!regFlag) {
                result.fail("注册失败,请联系系统管理人员");
            } else {
                // TODO AsyncManager.me()
                // AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.REGISTER, MessageUtils.message("user.register.success")));
                result.success("注册成功");
            }
        } else {
            result.fail("该用户名已被注册, 请换一个试试");
        }

        return result;
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid) {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            throw new CaptchaException();
        }
    }
}
